#include <LightMaps.h>

LightMaps::LightMaps(QWidget *parent) : QWidget(parent){
    pressed = false;
    snapped = false;
    invert = false;
    m_normalMap = new SlippyMap(this);

    QSizePolicy horiz(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding,QSizePolicy::Frame);

    this->setSizePolicy(horiz);

    connect(m_normalMap, SIGNAL(updated(QRect)), SLOT(updateMap(QRect)));
}


void LightMaps::setCenter(qreal lat, qreal lng) {
    m_normalMap->latitude = lat;
    m_normalMap->longitude = lng;
    m_normalMap->invalidate();
}


void LightMaps::toggleNightMode() {
    invert = !invert;
    update();
}


void LightMaps::updateMap(const QRect &r) {
    update(r);
}

void LightMaps::resizeEvent(QResizeEvent *) {
    m_normalMap->width = width();
    m_normalMap->height = height();
    m_normalMap->invalidate();
}


void LightMaps::paintEvent(QPaintEvent *event) {
    QPainter p;
    p.begin(this);
    m_normalMap->render(&p, event->rect());
    p.end();

    if (invert) {
        QPainter p(this);
        p.setCompositionMode(QPainter::CompositionMode_Difference);
        p.fillRect(event->rect(), Qt::white);
        p.end();
    }
}


void LightMaps::mousePressEvent(QMouseEvent *event) {
    if (event->buttons() != Qt::LeftButton)
        return;
    pressed = snapped = true;
    pressPos = dragPos = event->pos();
}


void LightMaps::mouseMoveEvent(QMouseEvent *event) {
    if (!event->buttons())
        return;

    if (!pressed || !snapped) {
        QPoint delta = event->pos() - pressPos;
        pressPos = event->pos();
        m_normalMap->pan(delta);
            if(abs(delta.x()) > 12 || abs(delta.y()) > 12){
                qDebug() << m_normalMap->latitude << m_normalMap->longitude;
             //   qDebug() << delta.x() << " x || " << delta.y() << " y";
             }
        return;

    } else {
        const int threshold = 10;
        QPoint delta = event->pos() - pressPos;
        if (snapped) {
            snapped &= delta.x() < threshold;
            snapped &= delta.y() < threshold;
            snapped &= delta.x() > -threshold;
            snapped &= delta.y() > -threshold;
        }
    }
}


void LightMaps::mouseReleaseEvent(QMouseEvent *) {
    update();
}

void LightMaps::wheelEvent(QWheelEvent *event){
    if(event->delta() < 0){
        if(m_normalMap->zoom > 5){
        m_normalMap->zoom = m_normalMap->zoom - 1;
        qDebug() << "New zoom:" << m_normalMap->zoom;
        m_normalMap->invalidate();
    }
        else{
            qDebug() << "Not zooming further out as this is min zoom level";
        }
    }
    else{
        if(m_normalMap->zoom < 16){
            m_normalMap->zoom = m_normalMap->zoom + 1;
            qDebug() << "New zoom:" << m_normalMap->zoom;
            m_normalMap->invalidate();
        }
        else{
            qDebug() << "Not zooming in further as this is the max zoom level";
        }
    }
    update();
}
